import Vue from 'vue'

/**
 * @description 配置文件
 * @param {Object} $alert
 */
import config from '@/common/w-config.js'

uni.$debouncess = function(func, wait) {
	console.log(1234);
	console.log({func,wait});
  let timeout;
  return function () {
    // 清空定时器
    if(timeout) clearTimeout(timeout);
    timeout = setTimeout(func, wait)
  }

}

uni.$debounce = function(fn, delay, immdiate = false) {
  let timer = null
  let isInvoke = false
  return function _debounce(...arg) {
	  console.log(...arg);
    if (timer) clearTimeout(timer)
    if (immdiate && !isInvoke) {
      fn.apply(this, arg)
      isInvoke = true
    } else {
      timer = setTimeout(() => {
        fn.apply(this, arg)
        isInvoke = false
      }, delay)
    }
  }
}


uni.$findClosestLyricBefore = function(lyricsArray, targetTime) {
  let closestLyric = lyricsArray[0];
  for (const lyric of lyricsArray) {
    if (lyric.time <= targetTime) {
      closestLyric = lyric;
    } else {
      break; // 假定歌词数组是按时间顺序排序的
    }
  }
  return closestLyric;
}

/**
 * 把歌词时间转成秒

 * @param {Object} time
 */
uni.$timeToSeconds = function(time) {
  const parts = time.split(':');
  if (parts.length === 2) {
    const minutes = parseInt(parts[0], 10);
    const secondsAndMilliseconds = parts[1].split('.');
    const seconds = parseInt(secondsAndMilliseconds[0], 10);
    return minutes * 60 + seconds;
  } else {
    return 0;
  }
}

/**
 * 将秒转换为 分:秒
 * @param {Number} s - 秒数
 */
uni.$sToHs = function(s) {
	//计算分钟
	//算法：将秒数除以60，然后下舍入，既得到分钟数
	let h;
	h = Math.floor(s / 60);
	//计算秒
	//算法：取得秒%60的余数，既得到秒数
	s = s % 60;
	//将变量转换为字符串
	h += '';
	s += '';
	//如果只有一位数，前面增加一个0
	h = h.length === 1 ? '0' + h : h;
	s = s.length === 1 ? '0' + s : s;
	return h + ':' + s;
}

/**
 * @description 弹框方法
 * @param {Object} $alert
 */
uni.$alert = function(title = config.ALERT_TITLE, duration = config.ALERT_TIME, icon = 'none') {
	uni.showToast({
		title,
		duration,
		icon
	})
}
uni.$deepCopy = function(obj) {
	// 如果是基本数据类型或null，则直接返回
	if (typeof obj !== 'object' || obj === null) {
		return obj;
	}

	// 如果是日期类型，则直接返回新的日期对象
	if (obj instanceof Date) {
		return new Date(obj);
	}

	// 如果是正则表达式，则直接返回新的正则表达式对象
	if (obj instanceof RegExp) {
		return new RegExp(obj);
	}

	// 如果是数组类型，则创建新的数组对象，并递归拷贝数组元素
	if (Array.isArray(obj)) {
		const newArr = [];
		for (let i = 0; i < obj.length; i++) {
			newArr[i] = uni.$deepCopy(obj[i]);
		}
		return newArr;
	}

	// 如果是对象类型，则创建新的对象，并递归拷贝对象属性
	const newObj = {};
	for (const key in obj) {
		if (obj.hasOwnProperty(key)) {
			newObj[key] = uni.$deepCopy(obj[key]);
		}
	}
	return newObj;
}

//友好展示播放量
uni.$friendNum = function(views) {
	views = parseInt(views);
	if (views < 1000) {
		return views;
	} else if (views < 1000000) {
		return (views / 1000).toFixed(1) + 'K';
	} else {
		return (views / 1000000).toFixed(1) + 'M';
	}
}

//判断是否微信登陆
uni.$isWechat = function() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true; // 微信中打开
	} else {
		return false; // 普通浏览器中打开
	}
}
/**
 * 获取Url指定的参数值
 */
uni.$getUrlParams = function(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

/**
 * 校验变量是否为空
 * @param {Object} variable
 */
uni.$isEmpty = function(variable) {
	if (variable === null || variable === undefined || variable === '') {
		return true;
	}
	// 如果是数组或对象，则判断其长度或键值对数量
	if (Array.isArray(variable) && variable.length === 0) {
		return true;
	}
	if (typeof variable === 'object' && Object.keys(variable).length === 0) {
		return true;
	}
	return false;
}

/**
	 * 请求
	 * @description ajax
	 * @param obj {Object} 请求参数对象
	 * @param obj.url {String}  请求地址
	 * @param obj.data {Object} 请求参数
	 * @param obj.type {String} 请求类型GET|POST
	 * @param obj.token {String} 是否校验登录
	 * @param obj.loading {Boolean}  是否加载提示
	 * @param obj.autoError {Boolean} 是否自动弹窗错误信息
	 * @param obj.contentType {String} 请求contentType
	 * @example 
	 let requestData = {
		url: '/api/ai_model/list',
		token: false,
		type: "get",
		data: {
			is_group:1
		}
	};
	uni.$ajax(requestData).then(res=>{
		
	}).cache(err=>{
		
	})
*/
uni.$ajax = function(obj) {
	if (!('autoError' in obj)) {
		obj.autoError = true;
	}
	let type = '';
	if (obj.type == '' || obj.type == undefined || obj.type == null) {
		type = 'POST';
	} else {
		type = obj.type;
	}
	let h = {};
	if (type == 'POST') {
		h = {
			"content-type": "application/json"
		}
	} else if (type == 'PUT') {
		h = {
			"content-type": "application/json"
		}
	} else if (type == 'DELETE') {
		h = {
			"content-type": "application/json"
		}
	} else {
		h = {
			"content-type": "application/x-www-form-urlencoded"
		}
	}
	if (obj.contentType) {
		h["content-type"] = obj.contentType;
	}
	if (obj.loading) {
		uni.showLoading({
			title: obj.loading === true ? '加载中' : obj.loading
		})
	}

	return new Promise((resolve, reject) => {
		h['token'] = uni.$gSyn('token');
		uni.request({
			url: config.PATH + obj.url,
			data: obj.data,
			method: type,
			header: h,
			withCredentials:true,
			success: res => {
				resolve(res.data);
			},
			fail: err => {
				if (obj.autoError) {
					uni.$alert(err.errMsg)
				}
				reject({
					code: 500,
					msg: err.errMsg
				})
			},
			complete: () => {
				if (obj.loading) {
					uni.hideLoading()
				}
			}

		})
	})
}

/**
 * @description 存储 同步方法
 * @param {Object} $sSyn
 */
uni.$sSyn = function(k, v) {
	uni.setStorageSync(k, v)
}

/**
 * @description 获取存储 同步方法
 * @param {Object} $gSyn
 */
uni.$gSyn = function(v) {
	return uni.getStorageSync(v)
}
/**
 * 设置富文本中的img图片宽度自适应
 * @param {富文本} html 
 */
uni.replaceImgWidth = function(html) {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
	return newContent;
}

/**
 * @description 删除存储 同步方法
 * @param {Object} $rSyn
 */
uni.$rSyn = function(v) {
	if (!v) return uni.$alert('请填写删除的key,方法:uni.$rSyn');
	uni.removeStorageSync(v);
}

/**
 * @description 跳转页面
 * @param {Object} $link
 */
uni.$link = function(url, t, Login, num) {
	//要判断是否登录
	if (Login == true) {
		let USERINFO = uni.$login();
		if (USERINFO == 1) {
			//没有登录要登录
			uni.navigateTo({
				url: config.LOGIN.URL
			})
			return
		}
	}

	let str = '';
	switch (t) {
		case 1:
			str = 'navigateTo'
			break;
		case 2:
			str = 'redirectTo'
			break;
		case 3:
			str = 'reLaunch';
			break;
		case 4:
			str = 'switchTab'
			break;
		case 5:
			str = 'navigateBack'
			break;
		default:
			str = 'navigateTo'
			break;
	}
	//返回上一级
	if (t == 5) {
		uni[str]({
			url: url,
			delta: num
		})
		return
	}
	//正常跳转
	uni[str]({
		url: url
	})
}

/**
 * @description 判断是否登录
 * @param {Object} $login
 */

uni.$login = function() {
	let USERINFO = uni.$gSyn(config.LOGIN.USERINFO);
	if (USERINFO) {
		return USERINFO;
	} else {
		return 1;
	}
}


/**
 * @description 生成唯一数
 * @param {Object} $uniqueNum
 */
uni.$uniqueNum = function(n) {
	return (n || '') + new Date().getTime().toString(36) + Math.random().toString(36).slice(2);
}

/**
 * @description 截取字符串
 * @param {Object} $strSplit
 */
uni.$strSplit = function(str, len) {
	let s = ''
	if (str.length > len) {
		s = str.substring(0, len)
	} else {
		s = str
	}
	return s
}

/**
 * @description 拨打电话
 * @param {Object} $call
 */
uni.$call = function(phone) {
	if (!phone) return uni.$alert('请填写手机号,方法:uni.$call')
	uni.makePhoneCall({
		phoneNumber: String(phone),
		success(e) {
			console.log("拨打成功", e);
		},
		fail(err) {
			console.log("拨打失败", err);
		}
	})
}

/**
 * @description 图片域名监测  有域名直接返回，没有域名直接添加 本地的图片地址
 * @param {Object} $imgUrl
 */
uni.$imgUrl = function(url) {
	url = url || ''
	return url.indexOf('http://') != -1 || url.indexOf('https://') != -1 ?
		url :
		config.IMGPATH + url;
}

/**
 * @description 上传图片
 * @param {Object} $uploadPic
 */
uni.$uploadPic = function(obj) {
	uni.showLoading({
		title: '上传中'
	})
	const _this = this;

	let url = !obj.url ? config.UPLADING_IMG_CONFIG.URL : obj.url;
	if (obj.count == undefined) {
		obj.count = 1
	}
	let id_c = 0;
	uni.chooseImage({
		count: obj.count,
		sizeType: ['copressed'],
		sourceType: ['album', 'camera'],
		success(res) {
			//因为有一张图片， 输出下标[0]， 直接输出地址
			uni.showLoading({
				title: '上传中'
			});
			var imgFiles = res.tempFilePaths;
			for (let i = 0; i < imgFiles.length; i++) {
				aa(imgFiles[i], imgFiles.length, url, config.PATH, id_c, i)
			}
		},
		fail(res) {
			uni.hideLoading();
		}
	})

	function aa(pic, len, url, u, id_c, index) {
		const _this = this;
		uni.uploadFile({
			url: u + url,
			filePath: pic,
			name: config.UPLADING_IMG_CONFIG.TYPE,
			header: {
				'token': uni.$gSyn('token')
			},
			success(res1) {
				uni.hideLoading();
				// 显示上传信息
				let data = JSON.parse(res1.data);
				if (data.code == 1) {
					obj.success(data, len, index)
				} else {
					uni.$alert(data.msg)
				}
			},
			fail(res) {
				uni.hideLoading();
				uni.$alert('上传图像失败')
			}
		})
	}
}

/**
 * @description 获取当前时间
 * @param {Object} $date
 */
uni.$date = function(t) {
	let date = new Date();
	let year = date.getFullYear(); //年
	let month = date.getMonth() + 1; //月
	month = month < 10 ? '0' + month : month;
	let day = date.getDate(); //天
	day = day < 10 ? '0' + day : day
	let hours = date.getHours(); //小时
	hours = hours < 10 ? '0' + hours : hours;
	let Minutes = date.getMinutes(); //分
	Minutes = Minutes < 10 ? '0' + Minutes : Minutes;
	let Seconds = date.getSeconds(); //秒
	Seconds = Seconds < 10 ? '0' + Seconds : Seconds;
	let timeS = date.getTime();
	let time1 = '';
	let dateList = '';
	let timeList = '';
	let monthData = ''
	if (t == '%') {
		time1 = year + '年' + month + '月' + day + '日 ' + hours + '时' + Minutes + '分' + Seconds + '秒';
		dateList = year + '年' + month + '月' + day + '日';
		monthData = year + '年' + month + '月';
		timeList = hours + '时' + Minutes + '分' + Seconds + '秒';
	} else {
		time1 = year + '-' + month + '-' + day + ' ' + hours + ':' + Minutes + ':' + Seconds;
		dateList = year + '-' + month + '-' + day;
		timeList = hours + ':' + Minutes + ':' + Seconds;
	}
	return {
		time: timeS,
		d: time1,
		year: year,
		month: month,
		day: day,
		hours: hours,
		Minutes: Minutes,
		Seconds: Seconds,
		dateList: dateList,
		timeList: timeList,
		monthData: monthData
	}
}

/**
 * @description 图片放大
 * @param {Object} $imgFd
 */
uni.$imgFd = function(obj) {
	// console.log(obj);
	//图片放大
	if (!obj.index) {
		obj.index = 0
	}
	uni.previewImage({
		current: obj.index,
		urls: obj.list,
		success: res => {},
		fail(err) {
			console.log(err);
		}
	})
}

/**
 * @description 时间转时间戳
 * @param {Object} $tTime
 */
uni.$tTime = function(t) {
	let date = new Date(t).getTime();
	return Math.round(date / 1000);
}

/**
 * @description 时间戳转时间
 * @param {Object} $timeT
 */
uni.$timeT = function(t, s) {
	if (s) {
		t = t
	} else {
		t = t * 1000
	}
	let date = new Date(t);
	let year = date.getFullYear(); //年
	let month = date.getMonth() + 1; //月
	month = month < 10 ? '0' + month : month
	let day = date.getDate(); //天
	day = day < 10 ? '0' + day : day
	let hours = date.getHours(); //小时
	hours = hours < 10 ? '0' + hours : hours;
	let Minutes = date.getMinutes(); //分
	Minutes = Minutes < 10 ? '0' + Minutes : Minutes;
	let Seconds = date.getSeconds(); //秒
	Seconds = Seconds < 10 ? '0' + Seconds : Seconds;
	return !t ? '' : year + '-' + month + '-' + day + ' ' + hours + ':' + Minutes + ':' + Seconds
}

/**
 * @description 根据经纬度获取地址 逆解析
 * @param {Object} $webLocation
 */

uni.$webLocation = function(res) {
	uni.request({
		header: {
			"Content-Type": "application/text"
		},
		//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
		url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' + res.longitude + ',' + res
			.latitude + '&key=' + config.GAODE_WEB_KEY + '&radius=1000&extensions=all',
		success(re) {
			if (re.statusCode === 200) {
				res.success(re.data.regeocode)
			} else {
				uni.$alert('获取信息失败，请重试！')
			}
		}
	});
}




/**
 * @description 把ni方法挂在到实例上
 * @param {Object} uni
 */
Vue.prototype.uni = uni;